import sqlite3
import getpass
#import sha


def getUser(curs):
    user=raw_input("please enter your username :")
    pwd=getpass.getpass("please enter your password :")
    #pwd=sha.new(str(pwd))     
    curs.execute("SELECT username, password from auth_user WHERE username='%s'" % (user))
    auth=curs.fetchall()
    #print "sha", auth[0][1]
    try:
        if auth[0][0]==user:
            if auth[0][1]==pwd:
                print "Hello", user
                return user
        else:                
            print "wrong password, please re-enter"
            x="false"
            return x
    except:
        print "username or password incorrect."
        x="false"
        return x          

def openBrianPgm(curs, reportId):
    import numpy as na
    import numpy.random as ra
    import sys
    import scipy.misc.pilutil as pu
    import matplotlib.pyplot as pyplot
    sys.path.insert(0,"../")
    #pass brian's program report from DB and location of images
    curs.execute("SELECT originalreport from pesubject WHERE id='%s'" % (reportId))
    report=curs.fetchall()
    report=report[0][0]
    
    import browseqt
    img = ra.normal(1,2,(32,128,128)).astype(na.int16)
    img = na.zeros((32,128,128),na.uint16)
    img[16,16:112,64] += na.arange(96)+16
    img[:,64,16:112] += na.arange(96)+16
    browseqt.call(data=img, winlevFile='winlevs.txt',labelFile="labelspe.txt",
                  colorFile='colors.txt', ReportText=report)


    #get location on Euler
    reportId=str(reportId)
    if len(reportId)==1:
        new_name="PE00000"+reportId
    elif len(reportId)==2:
        new_name="PE0000"+reportId
    else:
        new_name="PE000"+reportId
        
    loc="/HD1/Repository/Scrubbed/annotations/%s" % (new_name)

    #print report
    print "location of report: ", loc
         
    #call to Brian's program (report, loc)
    #annotation="what Brian's program returns"
    #return annotation,loc

def main():
    conn =sqlite3.connect('pedocUpdate_2.db')
    curs = conn.cursor()
    user=getUser(curs)
    if user!="false":
        conn =sqlite3.connect('pedocUpdate_2.db')
        curs = conn.cursor()
        curs.execute("SELECT PE_ID from annotations WHERE username='%s'" % (user))
        annot=curs.fetchall()
        ids=[] 
        for item in annot:
            ids.append(item[0])
            ids.sort()
            #print ids
            if len(ids)>0:
                for x in range (ids[-1]):
                    if x not in ids:
                        reportId=x
                        print "you will now begin annotating case ", reportId, "\n"
                        annotation=openBrianPgm(curs, reportId)
                        newAnnotation=annotation[0]
                        loc=annotation[1]
                        query="INSERT INTO annotations VALUES ('%s', '%s', 'annotaiton_text', '%s')" % (user,reportId,loc) 
                        curs.execute(query)
                        conn.commit()

                    else:
                        reportId=ids[-1]+1
                        print "you're last annotation was of case", ids[-1], "you will now begin annotating case ", reportId, "\n"
                        annotation=openBrianPgm(curs, reportId)
                        newAnnotation=annotation[0]
                        loc=annotation[1]
                        query="INSERT INTO annotations VALUES ('%s', '%s', 'annotaiton_text', '%s')" % (user,reportId,loc) 
                        print query  
                        curs.execute(query)
                        conn.commit()

            else:
                #get first file to annotate
                reportId=0
                print "this is the first time you logged in, you will begin by annotating case", reportId
                annotation=openBrianPgm(curs, reportId)
                newAnnotation=annotation[0]
                loc=annotation[1]
                query="INSERT INTO annotations VALUES ('%s', '%s', 'annotaiton_text', '%s')" % (user,reportId,loc) 
                curs.execute(query)
                conn.commit()


    else:
        main()

main()


